package com.unohacha.qqj.fzdr.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.qpg.superhttp.SuperHttp;
import com.qpg.superhttp.callback.SimpleCallBack;
import com.qpg.superhttp.request.UploadRequest;
import com.qpg.widget.common.ToastUtil;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.adapter.imgpicker.MyImgLibUploadImagePickerAdapter;
import com.unohacha.qqj.fzdr.bean.BaseBean;
import com.unohacha.qqj.fzdr.bean.ImgBean;
import com.unohacha.qqj.fzdr.bean.UnitBean;
import com.unohacha.qqj.fzdr.imp.MyCallBack;
import com.unohacha.qqj.fzdr.imp.UrlConfig;
import com.unohacha.qqj.fzdr.imp.XUtil;
import com.unohacha.qqj.fzdr.util.GlideImageLoaderForPicker;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.util.ToastUtils;
import com.unohacha.qqj.mylibrary.base.BaseActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ImgUploadActivity extends BaseActivity implements MyImgLibUploadImagePickerAdapter.OnRecyclerViewItemClickListener, View.OnClickListener {
    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.et_format)
    EditText etFormat;
    @BindView(R.id.et_kezhong)
    EditText etKezhong;
    @BindView(R.id.et_fukuan)
    EditText etFukuan;
    @BindView(R.id.et_extra)
    EditText etExtra;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_cate)
    TextView tvCate;
    @BindView(R.id.bt_submmit)
    TextView btSubmmit;
    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    @BindView(R.id.common_right_text)
    TextView commonRightText;
    @BindView(R.id.ll_classify)
    LinearLayout llClassify;
    @BindView(R.id.ll_label)
    LinearLayout llLabel;
    @BindView(R.id.tv_wheight)
    TextView tvWheight;
    @BindView(R.id.tv_width)
    TextView tvWidth;
    @BindView(R.id.ll_upload_pic)
    LinearLayout llUploadPic;
    private ArrayList<String> pickerList;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private MyImgLibUploadImagePickerAdapter imagePickerAdapter;
    public static ArrayList<ImageItem> selImageList; //当前选择的所有图片
    private int maxImgCount = 4;               //允许选择图片最大数
    private OptionsPickerView pvOptionsType,pvWeight,pvWidth;
    private int type = 3;
    private String fabricId;
    private ArrayList<String> weightList;
    private ArrayList<String> widthList;
    private int upload_type;
    private List<String> listPic;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_img_upload;
    }

    @Override
    protected void initData() {
        super.initData();
        commonTitle.setText("图片上传");
        commonBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        fabricId = getIntent().getStringExtra("fabricId");
        upload_type = getIntent().getIntExtra("upload_type",0);
        if(upload_type == 2){
            llUploadPic.setVisibility(View.GONE);
            recyclerView.setVisibility(View.GONE);

            etTitle.setText(Prefer.getInstance().getEditXH());
            if(Prefer.getInstance().getEditNature().equals("3")){
                tvType.setText("公开");
            }else{
                tvType.setText("私密");
            }
            
            tvCate.setText(Prefer.getInstance().getEditType());//性质
            etFormat.setText(Prefer.getInstance().getEditElement());
            tvWheight.setText(Prefer.getInstance().getEditWeight());
            tvWidth.setText(Prefer.getInstance().getEditWidth());
            etExtra.setText(Prefer.getInstance().getOtherContent());
            Log.d("deletaInfo",Prefer.getInstance().getEditType()+"1 "+Prefer.getInstance().getEditNature()+"2 "+Prefer.getInstance().getEditElement());
            listPic = (List<String>) getIntent().getSerializableExtra("listPic");

        }
        tvCate.setText(getIntent().getStringExtra("fabricName"));
        pvOptionsType = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tvType.setText(pickerList.get(options1));
                type = options1 + 3;
//                type=options1;
//                tvAllPrice.setText(listType.get(type).getPrice()*mCount+"");
            }
        }).setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.LTGRAY)
                .setCancelColor(Color.GRAY)
                .setSubmitColor(Color.RED)
                .setSubmitText("完成")
                .setTextColorCenter(Color.BLACK)
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();
        pickerList = new ArrayList<>();
        pvWeight = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tvWheight.setText(weightList.get(options1));
//                type = options1 + 3;
//                type=options1;
//                tvAllPrice.setText(listType.get(type).getPrice()*mCount+"");
            }
        }).setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.LTGRAY)
                .setCancelColor(Color.GRAY)
                .setSubmitColor(Color.RED)
                .setSubmitText("完成")
                .setTextColorCenter(Color.BLACK)
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();
        weightList = new ArrayList<>();
        pvWidth = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tvWidth.setText(widthList.get(options1));
//                type = options1 + 3;
//                type=options1;
//                tvAllPrice.setText(listType.get(type).getPrice()*mCount+"");
            }
        }).setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.LTGRAY)
                .setCancelColor(Color.GRAY)
                .setSubmitColor(Color.RED)
                .setSubmitText("完成")
                .setTextColorCenter(Color.BLACK)
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();
        widthList = new ArrayList<>();
        pickerList.add("公开");
        pickerList.add("私密");
        pvOptionsType.setPicker(pickerList);
        tvWheight.setOnClickListener(this);
        tvWidth.setOnClickListener(this);
        tvType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pvOptionsType.show();
            }
        });
        btSubmmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (etTitle.getText().toString().length() == 0) {
                    ToastUtil.showCustomToast("请输入标题");
                    return;
                }
                HashMap<String, String> map = new HashMap<>();
                map.put("token", Prefer.getInstance().getToken());
                map.put("id", "");
                map.put("supply_cate_id", fabricId);
                map.put("typeid", type + "");
                map.put("title", etTitle.getText().toString());
                map.put("nums", "");
                map.put("nums_company", "");
                map.put("price", "");
                map.put("price_company", "");
                map.put("breadth", etFukuan.getText().toString().trim());
                map.put("breadth_company", "");
                map.put("technology", "");
                map.put("content", etExtra.getText().toString());
                map.put("pay_type", "");
                map.put("gram_weight", etKezhong.getText().toString());
                map.put("gram_weight_company", "");
                map.put("component", etFormat.getText().toString());

                if(upload_type == 2){
                    map.put("list_pic", listToString(listPic));
                    SuperHttp.post("api/mycenter/myLibraryUpload")
                            .addParams(map)
                            .request(new SimpleCallBack<BaseBean<HashMap<String, String>>>() {
                                @Override
                                public void onSuccess(BaseBean<HashMap<String, String>> data) {

                                    ToastUtil.showCustomToast(data.getMessage());
                                    if (data.getCode() == 1) {
                                        payForPage(data.getData().get("order"));
                                    }
                                }

                                @Override
                                public void onFail(int errCode, String errMsg) {
                                    ToastUtils.showT("错了"+errMsg);
                                }
                            });
                }else{
                    mSubmit(map);
                }
                

            }
        });
        initImagePicker();
        selImageList = new ArrayList<>();
        imagePickerAdapter = new MyImgLibUploadImagePickerAdapter(this, selImageList, maxImgCount);
        imagePickerAdapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(imagePickerAdapter);

        getUnit();
    }

    public static String listToString(List<String> stringList) {
        if (stringList == null) {
            return null;
        }
        StringBuilder result = new StringBuilder();
        boolean flag = false;
        for (String string : stringList) {
            if (flag) {
                result.append(",");
            } else {
                flag = true;
            }
            result.append(string);
        }
        return result.toString();
    }

    //得到单位
    private void getUnit() {
        SuperHttp.post("api/supplyinfo/supplyPrompt\n")
                .addParam("supply_cate_id","1")
                .request(new SimpleCallBack<BaseBean<List<UnitBean>>>() {
                    @Override
                    public void onSuccess(BaseBean<List<UnitBean>> data) {
                        weightList.addAll(Arrays.asList(data.getData().get(9).getPrompt()));
                        pvWeight.setPicker(weightList);
                        
                        widthList.addAll(Arrays.asList(data.getData().get(5).getPrompt()));
                        pvWidth.setPicker(widthList);
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        ToastUtils.showT(errMsg);
                    }
                });
    }


    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoaderForPicker());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(false);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(maxImgCount);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                //打开选择,本次允许选择的数量
                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                Intent intent1 = new Intent(ImgUploadActivity.this, ImageGridActivity.class);
                startActivityForResult(intent1, REQUEST_CODE_SELECT);

                break;
//            default:
//                //打开预览
//                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
//                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
//                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
//                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
//                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
//                break;
        }
    }

    ArrayList<ImageItem> images = null;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    imagePickerAdapter.setImages(selImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    imagePickerAdapter.setImages(selImageList);
                }
            }
        }
    }


    private void mSubmit(final HashMap<String, String> map) {
        HashMap<String, String> parmas = new HashMap<>();
        parmas.put("token", Prefer.getInstance().getToken());
        parmas.put("type", "1");
        UploadRequest uploadRequest = SuperHttp.upload("api/filepic/filePic");
        if (images != null) {
            for (int i = 0; i < images.size(); i++) {
                uploadRequest.addImageFile("file" + i, new File(images.get(i).path));
            }
        } else {

            ToastUtil.showCustomToast("请选择图片");
            return;
        }

        uploadRequest.addParams(parmas);

        showLoading();
        uploadRequest.request(new SimpleCallBack<BaseBean<List<ImgBean>>>() {
            @Override
            public void onFail(int errCode, String errMsg) {
                ToastUtil.showCustomToast(errMsg);
                hideLoading();
            }

            @Override
            public void onSuccess(BaseBean<List<ImgBean>> data) {
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < data.getData().size(); i++) {
                    stringBuilder.append(data.getData().get(i).getId() + ",");
                }
                map.put("list_pic", stringBuilder.toString());
                SuperHttp.post("api/mycenter/myLibraryUpload")
                        .addParams(map)
                        .request(new SimpleCallBack<BaseBean<HashMap<String, String>>>() {
                            @Override
                            public void onSuccess(BaseBean<HashMap<String, String>> data) {

                                ToastUtil.showCustomToast(data.getMessage());
                                if (data.getCode() == 1) {
                                    payForPage(data.getData().get("order"));
                                }
                            }

                            @Override
                            public void onFail(int errCode, String errMsg) {

                            }
                        });

                hideLoading();
            }
        });
    }

    //发布支付
    private void payForPage(String order) {
        Map<String, Object> params = new HashMap<>();
        params.put("token", Prefer.getInstance().getToken());
        params.put("order", order);
        params.put("pay_type", 1);//支付类型：1-支付宝;2-微信;3-余额;4-银联支付;5-积分支付
        XUtil.Post(UrlConfig.SUPPLY_FILE_PAY, params, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Intent intent = new Intent(ImgUploadActivity.this, MyImgLibraryActivity.class);
                startActivity(intent);
//                finish();
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_wheight:
                if(weightList.size()<1){
                    ToastUtils.showT("暂无数据");
                }else{
                    pvWeight.show();
                }
                
                break;
            case R.id.tv_width:
                if(widthList.size()<1){
                    ToastUtils.showT("暂无数据");
                }else{
                    pvWidth.show();
                }
                break;
        }
    }

}
